`
https://leetcode.cn/problems/subarrays-with-k-different-integers/
`

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraysWithKDistinct = function (nums, k) {
  return solve(nums, k) - solve(nums, k + 1)
};

// 计算 nums 中不同整数的个数 >= k 的子数组个数
function solve(nums, k) {
  const n = nums.length
  const cnt = new Map()
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const n1 = nums[right++]
    cnt.set(n1, (cnt.get(n1) || 0) + 1)

    // 关注 left - 1 的合法性
    while (cnt.size === k) {
      const n2 = nums[left++]
      if (cnt.get(n2) === 1) cnt.delete(n2)
      else cnt.set(n2, cnt.get(n2) - 1)
    }

    // 有 left 个
    res += left
  }

  return res
}